package com.chen.blue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.blue.exception.e.TokenException;
import com.chen.blue.sysconfig.SystemConfig;

import java.util.Calendar;
import java.util.HashMap;

/**
 * Created By CLT On 2024/4/27.
 */
@SuppressWarnings("all")
public class TokenUtil {

    private static final SystemConfig systemConfig = SpringUtil.getBean(SystemConfig.class);

    /**
     * 根据用户ID和用户账号名生成token
     *
     * @param userId
     * @param username
     * @param sign
     * @return
     */
    public static String getToken(String username, String sign) {

        Calendar calendar = Calendar.getInstance();
        // 设置过期时间为1个小时
        calendar.add(Calendar.HOUR, systemConfig.getExpireTime());
        String token = JWT.create().withHeader(new HashMap<>())
                .withClaim("username", username)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(systemConfig.getTokenSign()));

        return token;

    }

    /**
     * 解析token
     *
     * @param token
     * @param sign
     * @return
     */
    public static String getUserName(String token, String sign) throws TokenException {

        //获取签名
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        //获取保存在客户端的令牌
        Claim username = null;

        try {
            DecodedJWT verify = build.verify(token);
            username = verify.getClaim("username");
            String newUsername = username.toString();
            /**
             * 添加当前用户权限,这边userName会多出双引号，去掉就行
             */
            return newUsername.substring(1, newUsername.length() - 1);
        } catch (TokenExpiredException e) {
            throw new TokenException("令牌过期");
        }

    }


}
